# Copyright (C) Nicola Bizzoca   2006/2007  <hannibal_smith@users.sourceforge.net>
# Copyright (C) Simone Economo   2006/2007  <ekoes@users.sourceforge.net>
# 
#    This file is part of Absynth-FTP.
#
#    Absynth-FTP is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Absynth-FTP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gtk, gobject, TreeView

class genericPopupMenuFactory:
    
    """ Oh fuck, ItemFactory is deprecated :( """
    
    def createMenu(self, items):
        self.accels = gtk.AccelGroup()
        self.factory = gtk.ItemFactory(gtk.Menu, "<menu>", self.accels)
        #self.__items = items
        self.__parseItems(items)
        #self.__addItems(items)
        
    """def addItem(self, data):
        #data { "label" : label, "image" : image }
        try:
            currentItem = gtk.ImageMenuItem(data["image"])
            #currentItem.set_image(data["image"])
        except:
            currentItem = gtk.MenuItem(data["label"])
            
        try:
            currentItem.add_accelerator
        except: pass
        
        if data["function"] is not None:
            currentItem.connect("activate", self.__onClick, data["function"])
            
            
        self.items.append(currentItem)
        self.widget.append(currentItem)
        currentItem.show()"""
        
    def __parseItems(self, items):
        
        self.__items = []
        
        def convertDataSource(base, parent = ""):
            try:
                label = base[0].replace(base[2], "_%s" % base[2])
            except:
                label = base[0]
            
            self.__items.append((
                "%s/%s" % (parent, label),
                base[1],
                base[3],
                0,
                base[4],
            ))     
                
            try:
                if type(base[5]) is tuple:
                    convertDataSource(base[5], "/%s" % base[0])
            except: pass
                    
        for item in items:
            convertDataSource(item)
            
        #print self.__items
        self.__makeMenu()
        
    def __makeMenu(self):
        self.factory.create_items(self.__items)
        self.widget = self.factory.get_widget("<menu>")
        self.items = list(self.widget)
        
    def connectTo(self, externalWidget):
        methods = {
            "widget-connect": "connect_object",
        }
        #getattr(widget, methods["widget-connect"])("popup_menu", self.__displayMenu)
        getattr(externalWidget, methods["widget-connect"])("event", self.__eventHandler, self.widget)
        
    def __eventHandler(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            #print event.button
            self.__displayMenu(event.button, event.time)
        
    def __displayMenu(self, button, activate_time, *data):
        self.widget.popup(None, None, None, button, activate_time, *data)
        
    def __onClick(self, widget, function):
        function()
        
        
        
        
        
        
        
class genericPopupMenu:
    
    def createMenu(self, items):
        self.__group = {
            "actions": gtk.ActionGroup("Actions"),
            "accels" : gtk.AccelGroup()
        }
        self.widget = gtk.Menu()

        self.__makeMenu(items)
        
        
    """def addItem(self, data):
        #data { "label" : label, "image" : image }
        try:
            currentItem = gtk.ImageMenuItem(data["image"])
            #currentItem.set_image(data["image"])
        except:
            currentItem = gtk.MenuItem(data["label"])
            
        try:
            currentItem.add_accelerator
        except: pass
        
        if data["function"] is not None:
            currentItem.connect("activate", self.__onClick, data["function"])
            
        self.items.append(currentItem)
        self.widget.append(currentItem)
        currentItem.show()"""
        
    def __convertDataSource(self, items):
        """
            (name, tooltip, image, key, underline, callback)
            
            #CONVERT TO:
            #('New', gtk.STOCK_NEW, '_New', '<control>N', 'Create a new file', menu_response),
            CONVERT TO:
            ('New', '_New', 'Create a new file', gtk.STOCK_NEW, '<control>N', menu_response),
        """
            
        actions = []           
        for item in items:
            try:
                label = item[0].replace(item[4], "_%s" % item[4])
            except:
                label = item[0]
                
            try:
                type = item[6]
            except:
                type = "item"
                
            try:
                checked = item[7]
            except:
                checked = False
            
            actions.append((
                item[0],
                label,
                item[1],
                item[2],
                item[3],
                item[4],
                item[5],
                type,
                checked,
            ))
            
        return actions
        #self.__actiongroup.add_actions(actions)
        #self.actions = self.__actiongroup.list_actions()
        #self.__data = actions
        
    def __makeMenu(self, items):
        
        actions = self.__convertDataSource(items)
        
        self.items = []
        for data in actions:
            if data[7] == "sep":
                currentItem = gtk.SeparatorMenuItem()
                currentItem.show()
            else:
                action = gtk.Action(*data[:4])
                self.__group["actions"].add_action_with_accel(action, data[4])
                action.set_accel_group(self.__group["accels"])
     
                if data[7] == "check":
                    action.set_menu_item_type(gtk.CheckMenuItem)
                    currentItem = action.create_menu_item()
                    try:
                        currentItem.set_active(data[8])
                    except: pass
                elif data[7] == "radio":
                    action.set_menu_item_type(gtk.RadioMenuItem)
                    currentItem = action.create_menu_item()
                    try:
                        currentItem.set_group(self.__group["radio"][0])
                    except:
                        self.__group["radio"] = []
                        self.__group["radio"].append(currentItem)
                    try:
                        currentItem.set_active(data[8])
                    except: pass
                elif data[7] == "item":
                    currentItem = action.create_menu_item()
                    

                
                if data[6] is not None:
                    currentItem.connect("activate", self.__onClick, data[6])

            self.items.append(currentItem)
            self.widget.append(currentItem)
        
        
    def connectTo(self, externalWidget):
        methods = {
            "widget-connect": "connect_object",
        }
        #getattr(widget, methods["widget-connect"])("popup_menu", self.__displayMenu)
        getattr(externalWidget, methods["widget-connect"])("event", self.__eventHandler, self.widget)
        
    def __eventHandler(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            #print event.button
            self.__displayMenu(event.button, event.time)
        
    def __displayMenu(self, button, activate_time, *data):
        self.widget.popup(None, None, None, button, activate_time, *data)
        
    def __onClick(self, widget, function):
        function()
        
class testSuite:
    
    def __init__(self):
        
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.connectEvents(self.window, {
             "delete_event" : self.delete,
             "destroy": self.destroy,
        })
        
        self.tree = TreeView.genericTreeView()
        self.tree.createTree("List", {
            "headers-visible"  : True,
            "headers-clickable": True,
            "rows-search"      : False,
            "rows-same-height" : False,
            "rows-alternate"   : True,
            "rows-reorder"     : True,
        })
        self.tree.setColumns([
            ("Filename", "image", str, True, True),
            ("Size", "text", str, True, False, 50),
            ("Last Edit", "text", str, True, True, None),
            ("Filename-hidden", "text", str, False, False, None, 0),
        ])
        self.tree.addListRow(["stock_folder", "4096", "aee", "usr"])
        self.menu = [genericPopupMenu(),]
        self.menu[0].createMenu([
            ("Nuovo", "Crea nuovo file", gtk.STOCK_NEW, "<control>N", "N", prova),
            ("Apri", "Apri file esistente", gtk.STOCK_OPEN, "<control>O", "O", None),
            ("Salva", "Salva file", gtk.STOCK_SAVE, "<control>S", "S", prova),
            ("", "", None, "", None, None, "sep"),
            ("Esci", "Rimuovi file", gtk.STOCK_QUIT, "<control>Q", "Q", prova),
        ])
        self.menu.append(genericPopupMenu())
        self.menu[1].createMenu([
            ("Homepage", "Apri da homepage", gtk.STOCK_HOME, "<control>H", "H", prova),
            ("Network", "Apri da network", gtk.STOCK_NETWORK, "<control>R", "r", prova),
            ("Preferenze", "Apri da preferenze", gtk.STOCK_PREFERENCES, "<control>P", "P", prova),
            ("Altro", "", None, "", None, None),
            ("", "", None, "", None, None, "sep"),
            ("Mostra files nascosti", "Mostra i files nascosti", None, "<Alt>f", "f", None, "check", True),
            ("", "", None, "", None, None, "sep"),
            ("Visualizza per nome", "Visualizza i file per nome", None, "<Alt>m", "m", None, "radio", True),
            ("Visualizza per ultima modifica", "Visualizza i file per ultima modifica", None, "<Alt>u", "u", None, "radio"),
            ("Visualizza per dimensioni", "Visualizza i file per dimensioni", None, "<Alt>d", "d", None, "radio"),
        ])
        self.menu[0].items[1].set_submenu(self.menu[1].widget)
        self.menu[0].connectTo(self.tree.widget)
        
        self.window.add(self.tree.widget)
        #self.tree.widget.show()
        self.window.show_all()
    
    def connectEvents(self, widget, events):
        for type,callback in events.items():
            widget.connect(type, callback)

    def delete(self, widget, event, data=None):
        #print "delete event occurred"
        return False

    def destroy(self, widget, data=None):
        #print "destroy signal occurred"
        gtk.main_quit()
        
    def runTest(self):
        gtk.main()
        
def prova():
    print "ciao"
        
if __name__ == "__main__": 
    GTK = testSuite()
    GTK.runTest()